/**
 * @fileOverview
 * @author iNahoo
 * @since 2019/12/2.
 */

const {createCanvas, createImageData, Image} = require('canvas');
const fs = require('fs');
const {BitMapUtil, Sobel} = require('../bitmap');

/**
 * @param w
 * @param h
 * @return {CanvasRenderingContext2D}
 */
function createContext(w, h) {
    const c = createCanvas(w, h);
    return c.getContext('2d');
}

function saveMatrix(m, p, transfer = BitMapUtil.getGrayImageData) {
    const im = transfer(m);
    const ctx = createContext(im.width, im.height);
    ctx.putImageData(im, 0, 0);
    fs.writeFileSync(p, ctx.canvas.toBuffer());
}

async function getImageData(p) {
    return new Promise((resolve, reject) => {
        fs.readFile(p, (err, bf) => {
            if (err) {
                reject(err);
            }

            const img = new Image();
            img.onload = () => {
                const ctx = createContext(img.width, img.height);
                ctx.drawImage(img, 0, 0);
                resolve(ctx.getImageData(0, 0, img.width, img.height));
            };

            img.onerror = reject;
            img.src = bf
        });
    })
}

const run = f => f();

// run(async () => {
//     const im = await getImageData(__dirname + '/../Sample_Icon.png');
//     const gray_matrix = BitMapUtil.getGrayMatrix(im.data, im.width, im.height);
//     const sobel_matrix = Sobel.sobelProcess(gray_matrix);
//     saveMatrix(
//         sobel_matrix,
//         __dirname + '/../Sample_Icon_sobel.jpg'
//     );
// });


run(async () => {
    const im = await getImageData(__dirname + '/../Sample_full_desktop.png');
    console.time('gray');
    const gray_matrix = BitMapUtil.getGrayMatrix(im.data, im.width, im.height);
    saveMatrix(
        gray_matrix,
        __dirname + '/../Sample_full_desktop_gray.jpg'
    );
    console.timeEnd('gray');

    console.time('sobel_matrix');
    const sobel_matrix = Sobel.sobelProcess(gray_matrix);

    saveMatrix(
        sobel_matrix,
        __dirname + '/../Sample_full_desktop_sobel.jpg'
    );
    console.timeEnd('sobel_matrix');

    console.time('bit_matrix');
    const bit_matrix = BitMapUtil.transferBitMatrix(sobel_matrix);
    saveMatrix(
        bit_matrix,
        __dirname + '/../Sample_full_desktop_sobel_bit128.jpg',
        BitMapUtil.getBitMatrixImageData
    );
    console.timeEnd('bit_matrix');

}).then(() => {
    console.log('SUCCESS')
}).catch(err => {
    console.error(err);
});

